# coding:utf-8 

'''
powered by Goldgom
before use this tool you may need to run:

    pip install pdf2docx             ||    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pdf2docx
    pip install python-docx          ||    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple python-docx
'''

from cmath import exp
from pdf2docx import Converter
from docx import Document
import re
import traceback
translator = None
sum_translate = 0
check = [" " ," "]

def init(url="com",proxy = None,translateWebsite = "Google"):
    global translator
    if translateWebsite == "Google":
        from google_trans_new_main.google_trans_new import google_translator
        if proxy == None :
            translator = google_translator(timeout=10,url_suffix=url)
        else:
            translator = google_translator(timeout=10,url_suffix=url,proxies=proxy)
    elif translateWebsite == "Baidu":
        from baidu_trans.baidu_translate import baidu_translator
        translator = baidu_translator()
def PDFToWord(PDFPath='a.pdf'):
    DOCXPath = 'out.docx'
    cv = Converter(PDFPath)
    cv.convert(DOCXPath) 
    cv.close()
def translatePDF(inputPath,outputPath):
    global check
    global sum_translate
    if inputPath == "":
        print("finding default")
        PDFToWord() 
    elif re.search("\.[p|P][d|D][f|F]$",inputPath):
        print("is pdf")
        PDFToWord(inputPath) 
    elif re.search("\.[d|D][o|O][c|C][x|X]$",inputPath):
        print("is docx")
        pre_docx = Document(inputPath)
        pre_docx.save("out.docx")
    else:
        assert("wrong file")
    docx = Document('out.docx')
    translation = translator.translate('hello world','zh-cn')
    print(translation)

    key = "${name}"
    value = "Ivan"
    for para in docx.paragraphs:
        try:            
            for run in para.runs:
                if needTranslation(run.text):
                    if run.text not in check:
                        check.append(run.text)
                        print("第{}次翻译".format(sum_translate))
                        sum_translate = sum_translate +1
                        temp = translator.translate(run.text,'zh-cn')
                        print("原文：")
                        print(run.text)
                        print("译文：")
                        print(temp)
                        if temp != run.text:
                            run.text = temp
            if len(check) > 50:
                check = check[25:]
        except:
            print(traceback.format_exc())
            continue
    docx.save(outputPath)
def needTranslation(text):
    RE_English = re.compile(r'[A-Za-z]',re.S)
    res = re.findall(RE_English,text)
    if "MOVE " in text:
        return False
    if not(len(res)):
        return False
    count = 0
    for ch in text:
        if u'\u4e00' <= ch <= u'\u9fff':
            return False
        if ch in "abcdefghijklmnopqrstuvwxyz":
            count = count + 1
    if count == 0 :
        return False
            
    return True
def reprocess(str):
    str = str.replace("。",".")
    return str
if __name__ == "__main__":
    inputPath = input("请输入PDF路径（空则默认为a.pdf）:\n")
    outputPath = "translated.docx"
    init(url="com",proxy={'http':'http://127.0.0.1:1080','https':'http://127.0.0.1:1080'})
    translatePDF(inputPath,outputPath)